package rest.jbpm.repository;

import java.util.List;
import org.hibernate.*;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.jbpm.api.cmd.*;
import org.slf4j.*;
import org.jbpm.pvm.internal.model.ProcessDefinitionImpl;
import org.jbpm.pvm.internal.util.CollectionUtil;


public class LatestDefinitions implements 
        Command<List<ProcessDefinitionImpl>> {
    
    private static final Logger log = LoggerFactory.getLogger(LatestDefinitions.class);
            
    @Override
    public List<ProcessDefinitionImpl> execute(Environment environment) throws Exception {
        
        Session session = null;
        SessionFactory sessionFactory = environment.get(SessionFactory.class);
        try {

            session = sessionFactory.openSession();
            List<ProcessDefinitionImpl> definitions = session
                    .createCriteria(ProcessDefinitionImpl.class, "definition")
                    //.addOrder(Order.desc("version"))
                    //.setProjection(Projections.groupProperty("key"))
                     .setResultTransformer(Criteria.ROOT_ENTITY)
                    .setFirstResult(0).list();
            
            log.info("{} tasks found",definitions.size());            
            
            return CollectionUtil.checkList(definitions,ProcessDefinitionImpl.class);
            
        } finally {
            if(session != null) session.close();
        }
    }
}
